package com.ethan.cj.ssm.filter;

import lombok.Setter;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * 处理请求乱码的过滤器
 * GET POST 均可处理
 */
public class CharacterEncodingFilter extends OncePerRequestFilter {
    @Setter
    private String encoding;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
//        request.setCharacterEncoding(encoding);
        request.setCharacterEncoding("ISO-8859-1");
        response.setCharacterEncoding(encoding);
        chain.doFilter(new GetHttpServletRequestWrapper(request, Charset.forName(encoding)), response);
//        chain.doFilter(request, response);
    }

    private class GetHttpServletRequestWrapper extends HttpServletRequestWrapper {

        private final Charset charset;

        /**
         * 获得被装饰对象的引用和采用的字符编码
         *
         * @param request
         * @param charset
         */
        GetHttpServletRequestWrapper(HttpServletRequest request, Charset charset) {
            super(request);
            this.charset = charset;
        }

        @Override
        public String getParameter(String name) {
            String value = super.getParameter(name);
            if (value != null) {
                value = new String(value.getBytes(StandardCharsets.ISO_8859_1), charset);
            }
            return value;
        }

        @Override
        public String[] getParameterValues(String name) {
            String[] values = super.getParameterValues(name);
            if (values != null) {
                for (int i = 0; i < values.length; i++) {
                    values[i] = new String(values[i].getBytes(StandardCharsets.ISO_8859_1), charset);
                }
            }
            return values;
        }
    }

}
